﻿using AForge.Video;
using System;
using System.Threading.Tasks;

namespace Clancy.Bl.VideoProvider
{
    internal class MJpegVideoSourceHandler : VideoSourceBase
    {
        private MJPEGStream m_MjpegStream;

        public MJpegVideoSourceHandler(string monikerString)
            : base(monikerString)
        {
        }

        protected override Task<bool> DoClose()
        {
            if (m_MjpegStream == null)
                return Task.FromResult(false);

            m_MjpegStream.Stop();
            return Task.FromResult(true);
        }

        protected override Task<bool> DoOpenVideoCapture(string monikerString)
        {
            m_MjpegStream = new MJPEGStream(monikerString);
            m_MjpegStream.NewFrame += MjpegStreamOnNewFrame;
            m_MjpegStream.Start();

            return Task.FromResult(m_MjpegStream.IsRunning);
        }

        private void MjpegStreamOnNewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            if (eventArgs == null)
                return;

            IncomingFrame.OnNext(eventArgs.Frame);
        }

        protected override void DoShowSettingsDialog()
        {
        }
    }
}